package io.cess.mqtt.demo.api;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import io.cess.mqtt.demo.config.MqttClientBean;
import io.cess.mqtt.demo.config.MqttConfig;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author wcl
 * @version 1.0
 * @date 2019/12/16 9:20 下午
 */
@RequestMapping("/api")
@RestController
@Slf4j
public class MqttController {


    @Autowired
    private   MqttClientBean mqttClientBean;

    @Autowired
    private MqttConfig mqttConfig;


    /**
     * 发送mqtt消息
     */
    @RequestMapping(value = "/sendMqttMsg",method = RequestMethod.POST)
    public void sendMqttMsg(String deviceId, String msg,String roomId){


        //设备id不为null标识要发送p2p消息
        if(StrUtil.isNotBlank(deviceId)){
            String p2pSendTopic = mqttConfig.getTopicId() + "/p2p/" + deviceId;
            MqttMessage mqttMessage = new MqttMessage(msg.getBytes());
            mqttMessage.setQos(mqttConfig.getQosLevel());
            try {
                mqttClientBean.getMqttClient().publish(p2pSendTopic, mqttMessage);
            } catch (MqttException e) {
                log.info("消息发送失败：{}", e.getMessage());
            }
        }
        //发送部分广播消息
        if(ObjectUtil.isNotNull(roomId)){
            MqttMessage message = new MqttMessage("hello mq4Iot pub sub msg".getBytes());
            message.setQos(mqttConfig.getQosLevel());
            /**
             *  发送普通消息时，topic 必须和接收方订阅的 topic 一致，或者符合通配符匹配规则
             */
            try {
                //发送普通广播时。将直播间Id作为二级主题发送
                mqttClientBean.getMqttClient().publish(mqttConfig.getTopicId()+"/"+roomId, message);
            } catch (MqttException e) {
                log.info("消息发送失败：{}", e.getMessage());
            }
        }
    }
}
